#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<assert.h>
#include<netinet/in.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>


void initSocket(){
    int tcp_socket_fd = socket(AF_INET,SOCK_STREAM,0);

    struct sockaddr_in local_addr = {0};
    local_addr.sin_family = AF_INET;
    local_addr.sin_port = htons(9999);
    local_addr.sin_addr.s_addr = inet_addr("127.0.0.1");

    bind(tcp_socket_fd, (struct sockaddr *)&local_addr,sizeof(local_addr));

    // listen for max client
    listen(tcp_socket_fd,5);

    printf("listen for client: ......");

    struct sockaddr_in client_addr = {0};
    while(1){
        int len = sizeof(client_addr);
        int new_socket = 0;
        new_socket = accept(tcp_socket_fd,(struct sockaddr *)&client_addr,&len);

        while (1)
        {
            char recvbuf[2048] = {0};
            int n = recvfrom(new_socket,recvbuf,2048,0,NULL,NULL);
            if(n <= 0){
                printf("one client over\n");
                break;
            }
            printf("%d:%s\n",new_socket,recvbuf);
            send(new_socket,"OK",2,0);
        }
        close(new_socket);
    }
    close(tcp_socket_fd);
}

int main(){
    initSocket();
    return 0;
}

